<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker clearable
          v-model="queryParams.createdAt"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="消息类型" prop="messageType">
        <el-select v-model="queryParams.messageType" placeholder="请选择消息类型" clearable>
          <el-option
            v-for="dict in sys_message_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
  <!-- 顶部操作区（新增） -->
    <div class="top-operation">
      <!-- 未读/已读/全部切换（新增） -->
      <el-tabs v-model="activeTab" type="card" @tab-change="handleTabChange">
        <el-tab-pane label="未读消息" name="unread" />
        <el-tab-pane label="已读消息" name="read" />
      </el-tabs>

      <!-- 批量操作与语音开关（新增） -->
      <div class="batch-operations">
        <el-switch
          v-model="voiceEnabled"
          active-text="语音开启"
          inactive-text="语音关闭"
          :active-value="true"
          :inactive-value="false"
          @change="handleVoiceChange"
        />
   
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['greenold-messages:messages:remove']"
        >删除</el-button>
     
        <el-button 
          type="primary" 
          plain 
          icon="Check" 
          @click="handleBatchRead"
          :disabled="!hasSelected"
        >
          全部已读
        </el-button>
        <el-button 
          type="danger" 
          plain 
          icon="Delete" 
          @click="handleBatchDelete"
          :disabled="!hasSelected"
        >
          全部删除
        </el-button>
      </div>
    </div>
    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="messagesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="消息ID" align="center" prop="id" /> -->
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="内容" align="center" prop="content" />
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="消息类型" align="center" prop="messageType">
        <template #default="scope">
          <dict-tag :options="sys_message_type" :value="scope.row.messageType"/>
        </template>
      </el-table-column>

         <!-- 新增：状态列（未读/已读） -->
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
          <el-tag type="primary" v-if="scope.row.status === '0'">未读</el-tag>
          <el-tag type="success" v-else>已读</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['greenold-messages:messages:edit']">修改</el-button> -->
  <!-- 新增：查看按钮 -->
          <el-button   link  type="primary" icon="Eye"   @click="handleView(scope.row)"   v-hasPermi="['greenold-messages:messages:view']" >查看</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['greenold-messages:messages:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改消息列表对话框 -->
    <!-- <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="messagesRef" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog> -->
  
   <!-- 新增：报警提醒弹窗 -->
   <el-dialog
      v-model="alarmVisible"
      title="报警提醒"
      width="380px"
      append-to-body
      :show-close="false"
      :modal="false"
      :close-on-click-modal="false"
      class="alarm-dialog"
    >
      <div class="alarm-content">
        <div class="alarm-icon">⚠️</div>
        <div class="alarm-info">
          <p>您有一条{{ alarmType === 'elder' ? '老人' : '设备' }}异常数据提醒，请及时处理</p>
          <div class="alarm-detail">
            <p>功能名称：{{ alarmData.functionName || '未知' }}</p>
            <p>数据值：{{ alarmData.value || '未知' }}</p>
            <p>所属产品：{{ alarmData.product || '未知' }}</p>
            <p>接入位置：{{ alarmData.location || '未知' }}</p>
          </div>
          <div class="countdown">将在 {{ countdown }} 秒后关闭</div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="alarmVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAlarmView">查看</el-button>
        </div>
      </template>
    </el-dialog>
      <!-- 新增：批量操作确认弹窗 -->
    <!-- <el-dialog
      v-model="confirmVisible"
      :title="confirmTitle"
      width="300px"
      append-to-body
    >
      <p>{{ confirmContent }}</p>
      <template #footer>
        <el-button @click="confirmVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmOperation"
        >
          确认
        </el-button>
      </template>
    </el-dialog> -->
  
  </div>
</template>

<script setup name="Messages">
// 新增：批量更新状态 batchUpdateStatus（已读） 
import { listMessages, getMessages, delMessages, addMessages, updateMessages,batchUpdateStatus} from "@/api/greenold-messages/messages"
import { ref, reactive, toRefs, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElNotification } from 'element-plus';
const { proxy } = getCurrentInstance()
const { sys_message_type } = proxy.useDict('sys_message_type')

const messagesList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
// 新增：未读/已读切换相关
const activeTab = ref('unread'); // 默认显示未读
const voiceEnabled = ref(true); // 语音默认开启
// 新增：报警弹窗相关
const alarmVisible = ref(false);
const countdown = ref(5);
const alarmType = ref(''); // 'elder'或'device'
const alarmData = ref({});


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    createdAt: null,
    messageType: null,
    status: '0' // 新增：默认查询未读（0=未读，1=已读）
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)
// 初始化（保留原有逻辑，新增报警监听）
onMounted(() => {
  getList(); // 原有列表查询
  simulateAlarm(); // 新增：模拟报警（实际项目替换为真实监听）
});
/** 查询消息列表列表 */
function getList() {
  loading.value = true
// 根据选项卡切换筛选状态（不影响原有搜索条件）
  if (activeTab.value === 'unread') {
    queryParams.value.status = '0'; // 未读
  } else if (activeTab.value === 'read') {
    queryParams.value.status = '1'; // 已读
  } else {
    queryParams.value.status = null; // 全部
  }
  listMessages(queryParams.value).then(response => {
    messagesList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(() => {
    loading.value = false;
    ElMessage.error('获取消息列表失败');
  });
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
    content: null,
    createdAt: null,
    messageType: null,
    receiverCode: null,
    status: null,
    remark: null,
    extend1: null,
    extend2: null
  }
  proxy.resetForm("messagesRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}
// 新增：查看消息（标记已读并跳转）
function handleView(row) {
  // 未读消息标记为已读（使用原有updateMessages API）
  if (row.status === '0') {
    updateMessages({ id: row.id, status: '1' }).then(() => {
      ElMessage.success('已标记为已读');
    });
  }
  // 根据消息类型跳转对应详情页（使用extend1/extend2存储跳转参数，不改动原有字段）
  if (row.messageType === 'todo') {
    router.push(`/todo/detail?id=${row.extend1}`); // extend1存储待办ID
  } else if (row.messageType === 'approved') {
    router.push(`/approved/detail?id=${row.extend1}`); // extend1存储已批ID
  } else if (row.messageType === 'abnormal') {
    // 异常消息：extend1区分老人/设备，extend2存储报警ID
    const path = row.extend1 === 'elder' ? '/alarm/elder' : '/alarm/device';
    router.push(`${path}?id=${row.extend2}`);
  } else {
    ElMessage.warning('暂不支持该类型消息查看');
  }
}

// /** 新增按钮操作 */
// function handleAdd() {
//   reset()
//   open.value = true
//   title.value = "添加消息列表"
// }

// /** 修改按钮操作 */
// function handleUpdate(row) {
//   reset()
//   const _id = row.id || ids.value
//   getMessages(_id).then(response => {
//     form.value = response.data
//     open.value = true
//     title.value = "修改消息列表"
//   })
// }

// /** 提交按钮 */
// function submitForm() {
//   proxy.$refs["messagesRef"].validate(valid => {
//     if (valid) {
//       if (form.value.id != null) {
//         updateMessages(form.value).then(response => {
//           proxy.$modal.msgSuccess("修改成功")
//           open.value = false
//           getList()
//         })
//       } else {
//         addMessages(form.value).then(response => {
//           proxy.$modal.msgSuccess("新增成功")
//           open.value = false
//           getList()
//         })
//       }
//     }
//   })
// }

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除消息列表编号为"' + _ids + '"的数据项？').then(function() {
    return delMessages(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}


/** 导出按钮操作 */
// function handleExport() {
//   proxy.download('greenold-messages/messages/export', {
//     ...queryParams.value
//   }, `messages_${new Date().getTime()}.xlsx`)
// }

// 新增：批量已读
function handleBatchRead() {
  confirmTitle.value = '全部已读';
  confirmContent.value = `确定要将选中的${ids.value.length}条消息标记为已读吗？`;
  confirmAction.value = 'read';
  confirmVisible.value = true;
}

// 新增：确认批量操作
function confirmOperation() {
  if (confirmAction.value === 'read') {
    // 批量更新状态为已读（调用新增API）
    batchUpdateStatus({ ids: ids.value, status: '1' }).then(() => {
      ElMessage.success('全部标记为已读成功');
      confirmVisible.value = false;
      getList();
    });
  } else if (confirmAction.value === 'delete') {
    // 批量删除（调用新增API）
    batchDelete(ids.value).then(() => {
      ElMessage.success('全部删除成功');
      confirmVisible.value = false;
      getList();
    });
  }
}

// 新增：语音开关切换
function handleVoiceChange(enabled) {
  voiceEnabled.value = enabled;
  ElMessage.success(enabled ? '语音提醒已开启' : '语音提醒已关闭');
}
// 新增：报警弹窗查看
function handleAlarmView() {
  alarmVisible.value = false;
  if (alarmType.value === 'elder') {
    router.push('/alarm/elder'); // 老人报警列表
  } else {
    router.push('/alarm/device'); // 设备报警列表
  }
}

// 新增：模拟报警（实际项目替换为WebSocket或接口轮询）
function simulateAlarm() {
  // 仅做示例：5秒后模拟一条报警
  setTimeout(() => {
    alarmType.value = 'elder';
    alarmData.value = {
      functionName: '心率',
      value: '160次/分钟',
      product: '智能手表',
      location: '101床位'
    };
    alarmVisible.value = true;
    
    // 语音播报（如果开启）
    if (voiceEnabled.value) {
      playVoice();
    }

    // 倒计时关闭
    startCountdown();
  }, 5000);
}


// 新增：语音播报
function playVoice() {
  const audio = new Audio();
  // 实际项目替换为真实语音文件
  audio.src = 'data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQQAAAAzMzMzMzMzMw==';
  audio.play().catch(err => console.log('语音播报失败:', err));
  
  // 文本提示（配合语音）
  ElNotification({
    title: '语音提醒',
    message: `⚠️ 您有一条${alarmType.value === 'elder' ? '老人' : '设备'}异常数据提醒，请及时处理`,
    duration: 5000
  });
}

// 新增：弹窗倒计时
function startCountdown() {
  countdown.value = 5;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
      alarmVisible.value = false;
    }
  }, 1000);
}
getList()
</script>
<style scoped>
/* 新增：顶部操作区样式 */
.top-operation {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 8px 0;
}

/* 新增：批量操作按钮样式 */
.batch-operations {
  display: flex;
  gap: 8px;
}

/* 新增：报警弹窗样式 */
.alarm-dialog {
  z-index: 9999 !important; /* 确保置顶 */
}
.alarm-content {
  display: flex;
  gap: 16px;
  padding: 10px 0;
}
.alarm-icon {
  font-size: 24px;
  color: #f56c6c;
  align-self: flex-start;
}
.alarm-info {
  flex: 1;
}
.alarm-detail {
  margin: 10px 0;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 13px;
}
.countdown {
  color: #f56c6c;
  font-size: 12px;
  text-align: right;
  margin-top: 8px;
}
</style>